package tzjz.example.listener;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mikuac.shiro.annotation.GroupMessageHandler;
import com.mikuac.shiro.annotation.MessageHandlerFilter;
import com.mikuac.shiro.annotation.PrivateMessageHandler;
import com.mikuac.shiro.annotation.common.Shiro;
import com.mikuac.shiro.common.utils.MsgUtils;
import com.mikuac.shiro.core.Bot;
import com.mikuac.shiro.dto.event.message.GroupMessageEvent;
import com.mikuac.shiro.dto.event.message.PrivateMessageEvent;
import com.mikuac.shiro.enums.AtEnum;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tzjz.example.entity.*;
import tzjz.example.service.IGroupQuService;
import tzjz.example.service.IParmSerice;
import tzjz.example.service.ISaoHuaSerice;
import tzjz.example.service.IWuPingService;
import tzjz.example.util.FreemarkeTools;
import tzjz.example.util.HttpUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

import static tzjz.example.util.GenerateImageUtil.generateSizeImage;
import static tzjz.example.util.GenerateImageUtil.generateSizeImageJiaoYiHang;

@Shiro
@Component
public class ExamplePlugin {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IParmSerice iParmSerice;

    @Autowired
    private ISaoHuaSerice iSaoHuaSerice;

    @Autowired
    private IGroupQuService iGroupQuService;
    @Autowired
    private IWuPingService iWuPingService;

    @PrivateMessageHandler
    @MessageHandlerFilter(cmd = "hi")
    public void fun1(Bot bot, PrivateMessageEvent event, Matcher matcher) {
        // // 构建消息
        // String sendMsg = MsgUtils.builder().face(66).text("Hello, love!!!!").build();
        // // 发送私聊消息
        // bot.sendPrivateMsg(event.getUserId(), sendMsg, false);
    }

    // 如果 at 参数设定为 AtEnum.NEED 则只有 at 了机器人的消息会被响应
    @GroupMessageHandler
    @MessageHandlerFilter(at = AtEnum.NEED)
    public void fun2(GroupMessageEvent event) {
        // 以注解方式调用可以根据自己的需要来为方法设定参数
        // 例如群组消息可以传递 GroupMessageEvent, Bot, Matcher 多余的参数会被设定为 null
        System.out.println(event.getMessage());
    }

    // @GroupMessageHandler
    // @MessageHandlerFilter(cmd = "早报")
    // public void zaobao(Bot bot, GroupMessageEvent event){
    //     Param zaobao = getUrl("zaobao");
    //     Param moyu = getUrl("moyu");
    //     Param zaobaotoken = getUrl("zaobaotoken");
    //
    //     String saoHua = getSaoHua();
    //     List<GroupQu> groupQus = getAllGroup();
    //
    //     String s = HttpUtil.get(zaobao.getValue() + "?token=" + zaobaotoken.getValue() + "&format=json");
    //     final JSONObject json = JSONObject.parseObject(s);
    //     String data = json.getString("data");
    //     if (!ObjectUtils.isEmpty(data)) {
    //         final JSONObject json1 = JSONObject.parseObject(data);
    //         String url = json1.getString("image");
    //
    //         String msg = MsgUtils.builder()
    //                 .img(url)  // 包含一张图片
    //                 .img(moyu.getValue())  // 包含一张图片
    //                 .text(saoHua)                 // 包含一段文本内容
    //                 .build();                       // 构建消息
    //
    //         for (GroupQu groupQu : groupQus) {
    //             // 调用 Bot 对象方法
    //             bot.sendGroupMsg(Long.parseLong(groupQu.getGroupId()), msg, false);
    //         }
    //     }
    // }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^随机名片\\s.+")
    public void suiji(Bot bot, GroupMessageEvent event){
        String[] text = event.getMessage().split(" ");
        String token = getToken();
        String server = "";
        String urlEx = "";
        if (text.length > 1) {
            server = text[1];
        }
        if (text.length > 2) {
            urlEx="&force="+text[2];
        }
        if (text.length > 3) {
            urlEx="&body="+text[3];
        }

        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param", "suijimingpian");
        Param one = iParmSerice.getOne(wrapper);
        String url = one.getValue();
        String result = HttpUtil.get(url + "?server=" + server +  "&token=" + token+urlEx);

        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            JSONObject jsonObject = JSONObject.parseObject(json.getString("data"));
            String msg = MsgUtils.builder().img(jsonObject.getString("showAvatar"))  // 包含一张图片
                    .build();                       // 构建消息
            bot.sendGroupMsg(event.getGroupId(), msg, false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查不到 睡大觉", false);
        }
    }
    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^招募\s?")
    public void zhaomu(Bot bot, GroupMessageEvent event){
        String token = getToken();
        //获取参数
        String plainText = event.getMessage();
        String[] text = plainText.split(" ");
        String server = "";
        String keyword = "";
        if (text.length == 2) {
            keyword = text[1];
            server = getGroup(event.getGroupId().toString()).getQu();
        }
        if (text.length == 3) {
            server = text[1];
            keyword = text[2];
        }
        //获取参数
        Param param =getUrl("zhaomu");
        Param ticket = getUrl("ticket");
        String url = param.getValue() + "?scale=1&robot=添只饺子&cache=1" + "&token=" + token + "&server=" + server + "&keyword=" + keyword + "&ticket=" + ticket.getValue();
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            JSONArray list = JSONObject.parseArray(json.getString("data"));
            // 构建图片
            String msg = MsgUtils.builder().img(list.getJSONObject(0).getString("url")).build();
            bot.sendGroupMsg(event.getGroupId(), msg, false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查询失败 累了 毁灭吧", false);
        }
    }


    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "开服")
    public void kaifu(Bot bot, GroupMessageEvent event){
        //获取参数
        Param param = getUrl("kaifu");
        //获取消息
        String plainText = event.getMessage();
        String[] text = plainText.split(" ");
        String server = "";
        if (text.length == 2) {
            server = text[1];
        }
        if (StringUtils.isEmpty(server)) {
            server = getGroup(event.getGroupId().toString()).getQu();
        } else if ("全服".equals(server)) {
            server = "";
        }
        String result = HttpUtil.get(param.getValue() + "?server=" + server);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            KaiFuDto kaiFuDto = json.getObject("data", KaiFuDto.class);
            String kaifu = "";
            if ("1".equals(kaiFuDto.getStatus())) {
                kaifu = kaifu + kaiFuDto.getServer() + "  " + "开服" ;
            } else {
                kaifu = kaifu + kaiFuDto.getServer() + "  " + "维护" ;
            }
            bot.sendGroupMsg(event.getGroupId(), kaifu, false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查询失败 累了 毁灭吧", false);
        }
    }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "公告")
    public void tongyong(Bot bot, GroupMessageEvent event){
        //获取参数
        Param param = getUrl("gonggao");
        String result = HttpUtil.get(param.getValue() + "?scale=1&robot=添只饺子&cache=1");
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            JSONArray list = JSONObject.parseArray(json.getString("data"));
            // 构建图片
            String msg = MsgUtils.builder().img(list.getJSONObject(0).getString("url")).build();
            bot.sendGroupMsg(event.getGroupId(), msg, false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查询失败 累了 毁灭吧", false);
        }
    }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^抓马")
    public void zhuama(Bot bot, GroupMessageEvent event){
        //获取消息
        String plainText = event.getMessage();
        String[] text = plainText.split(" ");
        //获取参数
        String server ="";
        String token =getToken();
        Param param = getUrl("zhuama");
        if (text.length == 2) {
            server = text[1];
        } else {
            server = getGroup(event.getGroupId().toString()).getQu();
        }
        String url = param.getValue() + "?pageIndex=1&pageSize=50&server=" + server + "&type=horse";
        String result = HttpUtil.get(url);
        final JSONObject json = JSONObject.parseObject(result);
        String data = json.getString("data");
        final JSONObject json1 = JSONObject.parseObject(data);
        String list = json1.getString("list");
        List<ZhuaMaDto> zhuaMaDtoList = (List<ZhuaMaDto>) JSONArray.parseArray(list, ZhuaMaDto.class);

        String message = "";
        //获取时间戳(十分钟前的)
        long time = System.currentTimeMillis() - 60000 * 10;
        List<ZhuaMaDto> collect = zhuaMaDtoList.stream().filter(p -> "zhcn_hd".equals(p.getEdition()) && p.getTime() * 1000 > time).collect(Collectors.toList());
        //5-10分钟播报
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        for (ZhuaMaDto zhuaMaDto : collect) {
            long startTime = zhuaMaDto.getTime() * 1000 + 60000 * 5;
            long endTime = zhuaMaDto.getTime() * 1000 + 60000 * 10;
            String start = sdf.format(new Date(Long.parseLong(String.valueOf(startTime))));
            String end = sdf.format(new Date(Long.parseLong(String.valueOf(endTime))));
            String str = zhuaMaDto.getContent();
            String address = str.substring(str.indexOf("有宝马良驹在") + 6, str.lastIndexOf("出没！"));
            message = message + address + "将有宝马良驹出现   " + start + "~" + end + "\n";
        }

        //npcChat
        String yinShanDaCaoYuan = "阴山大草原马场：\n";
        ZhuaMaDto yinShan = zhuaMaDtoList.stream().filter(p -> "216".equals(p.getMap_id())).collect(Collectors.toList()).get(0);
        String[] split = yinShan.getContent().split("\n");
        for (String str : split) {
            if (str.contains("分钟")) {
                String horse = str.substring(str.indexOf("下一匹") + 3, str.lastIndexOf("出世"));
                String fenZhong = str.substring(str.indexOf("还有") + 2, str.lastIndexOf("分钟"));
                long startTime = yinShan.getTime() * 1000 + 60000 * (Long.parseLong(fenZhong) + 5);
                long endTime = yinShan.getTime() * 1000 + 60000 * (Long.parseLong(fenZhong) + 10);
                String start = sdf.format(new Date(Long.parseLong(String.valueOf(startTime))));
                String end = sdf.format(new Date(Long.parseLong(String.valueOf(endTime))));
                if (System.currentTimeMillis() < endTime) {
                    yinShanDaCaoYuan = yinShanDaCaoYuan + horse + "   时间" + start + "~" + end + "\n";
                }
            }
        }
        if (!"阴山大草原马场：\n".equals(yinShanDaCaoYuan)) {
            message = message + yinShanDaCaoYuan;
        }


        String heiGeBiMaChang = "黑戈壁马场：\n";
        ZhuaMaDto heiGeBi = zhuaMaDtoList.stream().filter(p -> "217".equals(p.getMap_id())).collect(Collectors.toList()).get(0);
        String[] split1 = heiGeBi.getContent().split("\n");
        for (String str : split1) {
            if (str.contains("分钟")) {
                String horse = str.substring(str.indexOf("下一匹") + 3, str.lastIndexOf("出世"));
                String fenZhong = str.substring(str.indexOf("还有") + 2, str.lastIndexOf("分钟"));
                long startTime = heiGeBi.getTime() * 1000 + 60000 * (Long.parseLong(fenZhong) + 5);
                long endTime = heiGeBi.getTime() * 1000 + 60000 * (Long.parseLong(fenZhong) + 10);
                String start = sdf.format(new Date(Long.parseLong(String.valueOf(startTime))));
                String end = sdf.format(new Date(Long.parseLong(String.valueOf(endTime))));
                if (System.currentTimeMillis() < endTime) {
                    heiGeBiMaChang = heiGeBiMaChang + horse + "   时间" + start + "~" + end + "\n";
                }
            }
        }
        if (!"黑戈壁马场：\n".equals(heiGeBiMaChang)) {
            message = message + heiGeBiMaChang;
        }
        if (ObjectUtils.isEmpty(message)) {
            bot.sendGroupMsg(event.getGroupId(), "暂无抓马播报", false);
            return;
        }
        bot.sendGroupMsg(event.getGroupId(), message, false);
    }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "金价")
    public void jinjia(Bot bot, GroupMessageEvent event){
        String server =getGroup(event.getGroupId().toString()).getQu();
        String token =getToken();
        //获取参数
        Param param =getUrl("jin");
        String url = param.getValue() + "?server=" + server + "&limit=2"+"&token="+token;
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            List<Map> list = JSON.parseArray(json.getString("data").toString(), Map.class);
            String jin = server + "金价：";
            for (Map map : list) {
                if (ObjectUtil.isNotEmpty(map.get("wanbaolou"))) {
                    jin = jin + "\n" + "万宝楼：" + map.get("wanbaolou").toString();
                }
                if (ObjectUtil.isNotEmpty(map.get("tieba"))) {
                    jin = jin + "\n" + "贴吧：" + map.get("tieba").toString();
                }
                if (ObjectUtil.isNotEmpty(map.get("dd373"))) {
                    jin = jin + "\n" + "dd373：" + map.get("dd373").toString();
                }
                if (ObjectUtil.isNotEmpty(map.get("5173"))) {
                    jin = jin + "\n" + "5173：" + map.get("5173").toString();
                }
                if (ObjectUtil.isNotEmpty(map.get("uu898"))) {
                    jin = jin + "\n" + "uu898：" + map.get("uu898").toString();
                }
                break;
            }
            bot.sendGroupMsg(event.getGroupId(), jin, false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查询失败 累了 毁灭吧", false);
        }
    }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "日常")
    public void richaung(Bot bot, GroupMessageEvent event){
        Param param = getUrl("total");
        //获取消息
        String plainText = event.getMessage();
        String[] text = plainText.split(" ");
        int num = 0;
        String qu =getGroup(event.getGroupId().toString()).getQu();
        if (text.length > 1) {
            if ("明天".equals(text[1])) {
                num = 1;
            } else if ("后天".equals(text[1])) {
                num = 2;
            }
        }
        if (text.length == 3) {
            qu = text[2];
        }
        String result = HttpUtil.get(param.getValue() + "?server=" + qu + "&num=" + num);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            TotalDto totalDto = json.getObject("data", TotalDto.class);
            String[] split = totalDto.getDate().split("-");
            //家园声望
            String pre = "";
            if (ObjectUtil.isNotEmpty(totalDto.getPrestige())) {
                String[] prestige = totalDto.getPrestige();
                pre = String.join("、", prestige);
            }
            //武林通鉴
            String[] team = totalDto.getTeam();
            String team1 = String.join("\n", team);
            //美人图
            String huatu = "";
            if (!ObjectUtils.isEmpty(totalDto.getHuatu())) {
                huatu = "美人图∶" + totalDto.getHuatu() + "\n";
            }
            bot.sendGroupMsg(event.getGroupId(), "今天是" + split[0] + "年" + split[1] + "月" + split[2] + "日星期" + totalDto.getWeek() + "\n" +
                    "阵营∶跨服·烂柯山\n" +
                    "战场∶" + totalDto.getBattle() + "\n" +
                    "大战∶" + totalDto.getWar() + "\n" +
                    "家园声望∶" + pre + "\n" +
                    "武林通鉴∶" + team1 + "\n"
                    + huatu +
                    "活动∶" + totalDto.getSchool(), false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查询失败 累了 毁灭吧", false);
        }
    }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^cd\s(.*)?$")
    public void cd(Bot bot, GroupMessageEvent event) throws TemplateException, IOException {
        String plainText = event.getMessage();
        String[] text = plainText.split(" ");
        String server = "";
        String name = "";
        if (text.length == 3) {
            server = text[1];
            name = text[2];
        }
        if (text.length == 2) {
            name = text[1];
            server =getGroup(event.getGroupId().toString()).getQu();
        }
        //获取参数
        Param param = getUrl("cd");
        Param ticket =  getUrl("ticket");
        String token = getToken();
        String url = param.getValue() + "?&token=" + token + "&server=" + server + "&ticket=" + ticket.getValue() + "&name=" + name;
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            Map<String, Object> dict = JSON.parseObject(json.getString("data"), Map.class);
            if (ObjectUtil.isNotEmpty(dict.get("data"))) {
                List<Map> list = JSON.parseArray(dict.get("data").toString(), Map.class);
                for (Map map : list) {
                    String finBoss = "";
                    String unBoss = "";
                    if (ObjectUtil.isNotEmpty(map.get("bossProgress"))) {
                        List<Map> list1 = JSON.parseArray(map.get("bossProgress").toString(), Map.class);
                        for (Map map1 : list1) {
                            String s = map1.get("finished").toString();
                            if ("true".equals(map1.get("finished").toString())) {
                                finBoss = finBoss + "-" + map1.get("name");
                            } else {
                                unBoss = unBoss + "/" + map1.get("name");
                            }
                        }
                    }
                    map.put("finBoss", finBoss);
                    map.put("unBoss", unBoss);
                }
                dict.put("data", list);
            }
            //生成图片
            ModelMap modelMap = new ModelMap();
            modelMap.put("resume", dict);
            String templateName = "cd.ftl";
            String html = FreemarkeTools.ftlToString(modelMap, templateName);
            String htmlFilePath = "src/main/resources/html/cd.html";
            UUID uuid = UUID.randomUUID();
            String s = uuid.toString() + ".png";
            String imageFilePath = "src/main/resources/image/" +s ;
            String imgPath = FreemarkeTools.turnImage(html, htmlFilePath, imageFilePath, 1000, 600);
            // 构建图片
            String pre = getImgPath();
            imgPath=pre+s;
            String msg = MsgUtils.builder().img(imgPath).build();
            bot.sendGroupMsg(event.getGroupId(), msg, false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查询失败 累了 毁灭吧", false);
        }
    }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^交易行\s(.*)?$")
    public void jiaoYiHang(Bot bot, GroupMessageEvent event){
        //获取参数
        String plainText = event.getMessage();
        String[] text = plainText.split(" ");
        String result = "";
        String name = "";
        String size = "50";

        //是否输入长度
        String fu = getGroup(event.getGroupId().toString()).getQu();
        name = text[1];
        if (text.length == 3) {
            size = text[2];
        }

        //3. 获取mapper
        QueryWrapper<WuPing> wrapper = new QueryWrapper<>();
        wrapper.like("name", name);
        List<WuPing> wuPings =iWuPingService.selectByName(name);
        //搜索物品
        Param param = getUrl("souSuoWuPing");
        String s = HttpUtil.get(param.getValue() + "?keyword=" + name + "&page=1&limit="+size+"&client=std");
        JSONObject json = JSONObject.parseObject(s);
        List<WuPing> collect = new ArrayList<>();
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            Map<String, Object> params = JSONObject.parseObject(json.toJSONString());
            Map<String, Object> data3 = (Map<String, Object>) params.get("data");
            JSONArray ja = (JSONArray) data3.get("data");
            collect = ja.toJavaList(WuPing.class);
            for (WuPing wuPing : collect) {
                String id = wuPing.getId();
                QueryWrapper<WuPing> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("id", id);
                WuPing wuPing1 =iWuPingService.getOne(wrapper1);
                if (ObjectUtils.isEmpty(wuPing1)) {
                    iWuPingService.save(wuPing);
                }
            }
        }
        collect.addAll(wuPings);
        collect = collect.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(p -> p.getId()))), ArrayList::new));
        //搜索交易行
        if (collect.size() > 0) {
            List<Map<String, String>> list1 = new ArrayList<>();
            Map<String, String> map = new HashMap<>();
            map.put("0", fu);
            map.put("0", "");
            map.put("1", name);
            map.put("3", "");
            list1.add(map);

            for (int j = 0; j < collect.size(); j++) {
                result = HttpUtil.get("https://next2.jx3box.com/api/item-price/" + collect.get(j).getId() + "/detail?server=" + fu);
                JSONObject json1 = JSONObject.parseObject(result);
                if (!ObjectUtils.isEmpty(json1.getString("msg")) && "ok".equals(json1.getString("msg")) && !StringUtils.isEmpty(json1.getString("data"))) {
                    Map<String, Object> params = JSONObject.parseObject(json1.toJSONString());
                    Map<String, Object> data3 = (Map<String, Object>) params.get("data");
                    JSONArray ja = (JSONArray) data3.get("prices");
                    if (ObjectUtils.isEmpty(ja)) {
                        continue;
                    }
                    List<PricesDto> list = ja.toJavaList(PricesDto.class);
                    if (list.size() > 0) {
                        try {
                            if (collect.size() == 1) {
                                for (PricesDto pricesDto : list) {
                                    Map<String, String> map1 = new HashMap();
                                    map1.put("0", collect.get(j).getName());
                                    map1.put("1", pricesDto.getUnit_price() / 100000000 + " Z " + (pricesDto.getUnit_price() % 100000000) / 10000 + " J");
                                    map1.put("2", pricesDto.getN_count());
                                    Long time = pricesDto.getCreated();
                                    if (time == 0) {
                                        map1.put("3", "未知");
                                    } else {
                                        Date date = new Date(time * 1000);
                                        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        String time1 = sd.format(date);
                                        map1.put("3", time1);
                                    }
                                    list1.add(map1);
                                }
                            } else {
                                list = list.stream().sorted(Comparator.comparing(PricesDto::getUnit_price)).collect(Collectors.toList());
                                Map<String, String> map1 = new HashMap();
                                map1.put("0", collect.get(j).getName());
                                map1.put("1", list.get(0).getUnit_price() / 100000000 + " Z " + (list.get(0).getUnit_price() % 100000000) / 10000 + " J");
                                map1.put("2", list.get(0).getN_count());
                                Long time = list.get(0).getCreated();
                                if (time == 0) {
                                    map1.put("3", "未知");
                                } else {
                                    Date date = new Date(time * 1000);
                                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String time1 = sd.format(date);
                                    map1.put("3", time1);
                                }
                                list1.add(map1);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            UUID uuid = UUID.randomUUID();
            String s1 = uuid.toString() + ".jpg";
            String path = "src/main/resources/image/" +s1 ;

            generateSizeImageJiaoYiHang(list1, path, "不要频繁发起查询哦！");
            //发送图片
            String pre = getImgPath();
            path=pre+s1;
            String msg = MsgUtils.builder().img(path).build();
            bot.sendGroupMsg(event.getGroupId(), msg, false);
            return;
        }
        bot.sendGroupMsg(event.getGroupId(), "查询不到物品 检查名称是否正确", false);
    }


    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "功能")
    public void gongNeng(Bot bot, GroupMessageEvent event){
        String path="gongneng1.jpg";
        String path1="gongneng2.png";
        Random r = new Random();
        String address= r.nextBoolean() ? path1 : path;
        try {
            if (!StringUtils.isEmpty(address)) {
                String pre = getImgPath();
                address=pre+address;
                String msg = MsgUtils.builder().img(address).build();
                bot.sendGroupMsg(event.getGroupId(), msg, false);
            }
        }catch (Exception e) {
        }
    }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "骚话")
    public void saohua(Bot bot, GroupMessageEvent event){
        String saoHua = getSaoHua();
        bot.sendGroupMsg(event.getGroupId(), saoHua, false);
    }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^奇遇\s(.*)?$")
    public void qiyu(Bot bot, GroupMessageEvent event)  {
        String token = getToken();
        //获取参数
        String plainText = event.getMessage();
        String[] text = plainText.split(" ");
        String result = "";
        String name = "";
        String fu = "";
        Param param = getUrl("qiYuUrl");
        //是否输入区服
        if (text.length == 2) {
           fu = getGroup(event.getGroupId().toString()).getQu();
            name = text[1];
            result = HttpUtil.get(param.getValue() + "?server=" + fu + "&name=" + name + "&token=" + token);
        }
        if (text.length == 3) {
            name = text[2];
            fu = text[1];
            result = HttpUtil.get(param.getValue() + "?server=" + fu + "&name=" + name + "&token=" + token);
        }


        if (!StringUtils.isEmpty(result)) {
            final JSONObject json = JSONObject.parseObject(result);
            if (StringUtils.isEmpty(json.getString("data"))) {
                bot.sendGroupMsg(event.getGroupId(), fu + "的" + name + "侠士查询不到奇遇，请继续努力", false);
                return;
            }
            if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
                JSONArray ja = json.getJSONArray("data");
                List<QiYuDto> collect = ja.toJavaList(QiYuDto.class);
                List<QiYuDto> list = collect.stream().filter(p -> !"3".equals(p.getLevel())).collect(Collectors.toList());
                if (list.size() == 0) {
                    bot.sendGroupMsg(event.getGroupId(), fu + "的" + name + "侠士查询不到奇遇，请继续努力", false);
                }
                try {
                    String[][] tableData2 = new String[list.size() + 1][3];
                    tableData2[0][0] = fu;
                    tableData2[0][1] = name;
                    for (int i = 0; i < list.size(); i++) {
                        tableData2[i + 1][0] = list.get(i).getName();
                        tableData2[i + 1][1] = list.get(i).getEvent();
                        Long time = list.get(i).getTime();
                        if (time == 0) {
                            tableData2[i + 1][2] = "未知";
                        } else {
                            Date date = new Date(time * 1000);
                            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String time1 = sd.format(date);
                            tableData2[i + 1][2] = time1;
                        }
                    }
                    UUID uuid = UUID.randomUUID();
                    String s = uuid.toString() + ".jpg";
                    String path = "src/main/resources/image/" +s ;
                    generateSizeImage(tableData2, path, "不要频繁发起查询哦！");
                    // 构建图片
                    String pre = getImgPath();
                    path=pre+s;
                    String msg = MsgUtils.builder().img(path).build();
                    bot.sendGroupMsg(event.getGroupId(), msg, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                bot.sendGroupMsg(event.getGroupId(), "查询失败 累了 毁灭吧", false);
            }
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查询失败 累了 毁灭吧", false);
        }
    }


    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^物价\s(.*)?$")
    public void wujia(Bot bot, GroupMessageEvent event) throws TemplateException, IOException {
        String token = getToken();
        //获取参数
        String plainText = event.getMessage();
        String[] text = plainText.split(" ");
        String name = text[1];
        Param param = getUrl("wujia");
        String url =param.getValue() + "?&token=" + token +"&name=" + name;

        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            Map<String, Object> dict = JSON.parseObject(json.getString("data"), Map.class);
            Map<String, Object> wujia=new HashMap<>();
            wujia.put("view",dict.get("view").toString());
            wujia.put("name",dict.get("name"));
            wujia.put("subalias",dict.get("subalias"));
            wujia.put("desc",dict.get("desc"));
            wujia.put("raw",dict.get("raw"));

            List<Map<String, Object>> list=new ArrayList<>();

            if (ObjectUtil.isNotEmpty(dict.get("data"))) {
                List<Map<String, Object>> dict1 = JSON.parseObject(dict.get("data").toString(), List.class);
                for (int i = 0; i <= 4; i++) {
                    Map<String, Object> map =new HashMap<>();
                    if(ObjectUtil.isNotEmpty(dict1.get(i))) {
                        switch (i) {
                            case 0:
                                map.put("zone","电信区");
                                break; 
                            case 1:
                                map.put("zone","双线区");
                                break;
                            case 2:
                                map.put("zone","无界区");
                                break; 
                            case 3:
                                map.put("zone","公示期");
                                break;
                            default:
                                map.put("zone","正售中");
                                break;
                        }
                        map.put("data",dict1.get(i));
                        list.add(map);
                    }
                }

            }

            wujia.put("history", list);
            //生成图片
            ModelMap modelMap = new ModelMap();
            modelMap.put("weujia", wujia);
            String templateName = "wujia.ftl";
            String html = FreemarkeTools.ftlToString(modelMap, templateName);
            String htmlFilePath = "src/main/resources/html/wujia.html";
            UUID uuid = UUID.randomUUID();

            String s = uuid.toString() + ".png";
            String imageFilePath = "src/main/resources/image/" +s ;

            String imgPath = FreemarkeTools.turnImage(html, htmlFilePath, imageFilePath, 1000, 2000);
            // 构建图片
            String pre = getImgPath();
            imgPath=pre+s;
            String msg = MsgUtils.builder().img(imgPath).build();
            bot.sendGroupMsg(event.getGroupId(), msg, false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查不到 睡大觉", false);
        }
    }
    //监听群组
    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^名剑\s(.*)?$")
    public void mingJian(Bot bot, GroupMessageEvent event) throws TemplateException, IOException {

        String token = getToken();
        String fuServer = getGroup(event.getGroupId().toString()).getQu();
        String ticket = getTicket();
        //获取参数
        String plainText = event.getMessage();
        String[] text = plainText.split(" ");
        String name = "";
        String server = "";
        String mode = "";
        if (text.length == 4) {
            server = text[1];
            name = text[2];
            mode = text[3];
        }
        if (text.length == 3) {
            if ("22".equals(text[2]) || "33".equals(text[2]) || "55".equals(text[2])) {
                name = text[1];
                mode = text[2];
                if (!ObjectUtils.isEmpty(fuServer)) {
                    server = fuServer;
                }
            } else {
                server = text[1];
                name = text[2];
            }
        }
        if (text.length == 2) {
            name = text[1];
            if (!ObjectUtils.isEmpty(fuServer)) {
                server = fuServer;
            }
        }
        Param param = getUrl("mingjian");
        String url = "";
        if (ObjectUtils.isEmpty(mode)) {
            url = param.getValue() + "?&token=" + token + "&server=" + server + "&ticket=" + ticket + "&name=" + name + "&mode=33" ;
        } else {
            url = param.getValue() + "?&token=" + token + "&server=" + server + "&ticket=" + ticket + "&name=" + name + "&mode=" + mode;
        }
        String result = HttpUtil.get(url);
        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            Map<String, Object> dict = JSON.parseObject(json.getString("data"), Map.class);
            if (ObjectUtil.isNotEmpty(dict.get("performance"))) {
                Map<String, Object> dict1 = JSON.parseObject(dict.get("performance").toString(), Map.class);
                for (String s : dict1.keySet()) {
                    Map map = JSON.parseObject(dict1.get(s).toString(), Map.class);
                    map.put("all",s);
                    dict.put("total", map);
                }
            }
            if (StringUtils.isEmpty(dict.get("san"))) {
                dict.put("san", new HashMap<>());
            }
            if (StringUtils.isEmpty(dict.get("er"))) {
                dict.put("er", new HashMap<>());
            }
            if (StringUtils.isEmpty(dict.get("wu"))) {
                dict.put("wu", new HashMap<>());
            }
            List<Map> list = JSON.parseArray(dict.get("history").toString(), Map.class);
            for (Map map : list) {
                Long startTime = Long.parseLong(map.get("startTime").toString());
                Long endTime = Long.parseLong(map.get("endTime").toString());
                Long time = endTime - startTime;
                map.put("time", time);
                Date date = new Date(endTime * 1000);
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time1 = sd.format(date);
                map.put("endDay", time1);
                String won = "";
                if ("true".equals(map.get("won").toString())) {
                    won = "胜利";
                } else {
                    won = "失败";
                }
                if ("true".equals(map.get("mvp").toString())) {
                    won = won + ":mvp";
                }
                map.put("result", won);
            }
            dict.put("history", list);
            //生成图片
            ModelMap modelMap = new ModelMap();
            modelMap.put("resume", dict);
            String templateName = "mingjian.ftl";
            String html = FreemarkeTools.ftlToString(modelMap, templateName);
            String htmlFilePath = "src/main/resources/html/mingjian.html";
            UUID uuid = UUID.randomUUID();

            String s = uuid.toString() + ".png";
            String imageFilePath = "src/main/resources/image/" +s ;
            String imgPath = FreemarkeTools.turnImage(html, htmlFilePath, imageFilePath, 1000, 1000);
            // 构建图片
            String pre = getImgPath();
            imgPath=pre+s;
            String msg = MsgUtils.builder().img(imgPath).build();
            bot.sendGroupMsg(event.getGroupId(), msg, false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查不到 睡大觉", false);
        }
    }


    //监听群组
    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^名片\s(.*)?$")
    public void mingPian(Bot bot, GroupMessageEvent event) {
        String[] text = event.getMessage().split(" ");
        String token = getToken();
        String server = "";
        String name = "";
        if (text.length > 2) {
            server = text[1];
            name = text[2];
        } else {
            name = text[1];
            server = getGroup(event.getGroupId().toString()).getQu();
        }

        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param", "mingpianUrl");
        Param one = iParmSerice.getOne(wrapper);
        String url = one.getValue();
        String result = HttpUtil.get(url + "?server=" + server + "&name=" + name + "&token=" + token);

        //返回参数处理
        final JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code")) && !StringUtils.isEmpty(json.getString("data"))) {
            JSONObject jsonObject = JSONObject.parseObject(json.getString("data"));
            String msg = MsgUtils.builder().img(jsonObject.getString("showAvatar"))  // 包含一张图片
                    .build();                       // 构建消息
            bot.sendGroupMsg(event.getGroupId(), msg, false);
        } else {
            bot.sendGroupMsg(event.getGroupId(), "查不到 睡大觉", false);
        }

    }


    // 同时监听群组及私聊消息 并根据消息类型（私聊，群聊）回复
    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^猜成语\s(.*)?$")
    public void idiom(Bot bot, GroupMessageEvent event) {
        String[] text = event.getMessage().split(" ");
        String idiom = "";
        long groupId = event.getGroupId();
        if (text.length != 2) {
            return;
        }
        String word = text[1];

        Object result = redisTemplate.opsForValue().get("groupId" + idiom);
        if (ObjectUtils.isEmpty(result)) {
            idiom = getIdiom(groupId);
        } else {
            JSONObject json = JSONObject.parseObject(result.toString());
            idiom = json.getString("words");
        }

    }


    private String getIdiom(long groupId) {
        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param", "idiomUrl");
        Param one = iParmSerice.getOne(wrapper);
        String url = one.getValue();
        String result = HttpUtil.get(url);

        //返回参数处理
        JSONObject json = JSONObject.parseObject(result);
        if (!ObjectUtils.isEmpty(json.getString("code")) && "200".equals(json.getString("code"))) {
            redisTemplate.opsForValue().set(groupId + "idiom", json.toJSONString());
            redisTemplate.opsForValue().set(groupId + "words", json.getString("words"));
            redisTemplate.opsForValue().set(groupId + "pingyin", json.getString("pingyin"));
        }
        return json.getString("words");
    }

    private String getSaoHua() {
        SaoHua saoHua = iSaoHuaSerice.selectByRandom();
        return saoHua.getText();
    }


    private Param getUrl(String url) {
        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param", url);
        Param param = iParmSerice.getOne(wrapper);
        return param;
    }

    private String getToken() {
        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param", "token");
        Param one = iParmSerice.getOne(wrapper);
        return one.getValue();
    }


    private String getTicket() {
        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param", "ticket");
        Param one = iParmSerice.getOne(wrapper);
        return one.getValue();
    }


    private GroupQu getGroup(String groupId) {
        QueryWrapper<GroupQu> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id", groupId);
        GroupQu groupQu = iGroupQuService.getOne(wrapper);
        return groupQu;
    }

    private String getImgPath() {
        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param", "imgPath");
        Param one = iParmSerice.getOne(wrapper);
        return one.getValue();
    }

    private List<GroupQu> getAllGroup() {
        QueryWrapper<GroupQu> wrapper = new QueryWrapper<>();
        wrapper.eq("zaobao", "1");
        List<GroupQu> list = iGroupQuService.list(wrapper);
        return list;
    }
}
